# -*- coding: utf-8 -*-
from __future__ import print_function

import time
from decimal import Decimal

from dtrader.event import EventType
from dtrader import logger

try:
    import Queue as queue
except ImportError:
    import queue


class LiveTrade(object):

    #===========================================================================
    # 初始化设置
    #===========================================================================
    def __init__(
        self,
        price_handler,
        portfolio,
        strategie,
        heartbeat=0.1
    ):
        """
        交易主程序
        :param dtrader.price_handler.AbstractPriceHandler price_handler:
        :param dtrader.portfolio.AbstractPriceHandler portfolio_handler:
        :param strategie:
        :param heartbeat:
        """

        self.price_handler = price_handler
        self.portfolio = portfolio
        self.strategie = strategie
        self.heartbeat = heartbeat
        self.events_queue = price_handler.events_queue
        self.cur_time = None
        self.__logger = logger.getLogger(self.__class__.__name__)
    #===========================================================================
    # 创建事件循环，进行回测，循环会休息设定的"heartbeat"时间
    #===========================================================================
    def trade(self):

        print("Running Trade...")
        while True:
            try:
                event = self.events_queue.get(False)
            except queue.Empty:
                pass
            else:
                if event is not None:
                    self.__logger.debug("get Event:%s"%(event))
                    if event.type == EventType.TICK:
                        self.strategie.on_tick(event)
                    elif event.type == EventType.BAR:
                        self.strategie.on_bar(event)
                    elif event.type == EventType.FILL:
                        self.portfolio.on_fill(event)
                    else:
                        raise NotImplemented("Unsupported event.type '%s'" % event.type)
            time.sleep(self.heartbeat)
